package net.receiving;

import net.IncomingMessage;
import net.receiving.converter.Converter;

import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.SocketException;
import java.io.IOException;

import util.Config;

public class IncomingMessageUDPFactory implements IncomingMessageFactory {

    //TODO: FIX BUFFER.
    private static final int BUFFER_SIZE = 600 * 600;

    private final DatagramSocket udpSocket;

    public IncomingMessageUDPFactory() {
        try {
            udpSocket = new DatagramSocket(Config.getInstance().getReceivePort());
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    public IncomingMessage receive() {
        DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
        try {
            udpSocket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int len = packet.getLength();
        byte[] data = packet.getData();
        IncomingMessage message = Converter.createIncomingMessage(data, len, packet.getAddress());
        //DataBaseClient.getInstance().add(message.sourceAddress.getName(), packet.getAddress());
        return message;
    }

}
